package money.pot.app;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MoneyPotApp<Button> extends Activity {
	// the Activity or Application that is creating an object from this class.
	Context context;

	// the text fields that users input new data into
	EditText Groupname, MemberName;

	// the table that displays the data
	TableLayout dataTable;
 	
	// the class that opens or creates the database and makes sql calls to it
	AABDatabaseManager db;
	
	String groupName;
	long groupId;
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);

	    return true;
	}
	
	// MENU
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.deposit_button:
	    	setContentView(R.layout.view10_dp);
	        return true;
	        
	    case R.id.withdrawal_button:
	    	setContentView(R.layout.view07_wd);
	        return true;
	        
	    case R.id.overview_button:
	    	setContentView(R.layout.view13_overview);
	        return true;
	        
	    case R.id.editgrp_button:
	    	setContentView(R.layout.view05_editgrp);
	        return true;
	        
	    case R.id.settings_button:
	    	// settings
	        return true;
	        
	    case R.id.about_button:
	    	// a boot
	        return true;
	        
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}	

	
    /** Called when the activity is first created. */
		
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	try { // Gives a better error description
	    	super.onCreate(savedInstanceState);
	        setContentView(R.layout.view01_main);         
	              
	        // create the database manager object
	        db = new AABDatabaseManager(this);
	        
	        @SuppressWarnings("unchecked")
			final Button button1 = (Button) findViewById(R.id.button1); // Start Application
	        ((View) button1).setOnClickListener(new View.OnClickListener() {
	            @Override
				public void onClick(View v) {
	                setContentView(R.layout.view02_getstart);    
	                
	                @SuppressWarnings("unchecked")
	        		final Button button1 = (Button) findViewById(R.id.button1); // Create New Group
	                ((View) button1).setOnClickListener(new View.OnClickListener() {
	                    @SuppressWarnings("unchecked")
						@Override
						public void onClick(View v) {
	                        setContentView(R.layout.view03_newgrp);
	                        Groupname= 		(EditText)findViewById(R.id.text_field_one);
	            			final Button button1 = (Button) findViewById(R.id.add_group_button); // Start Application
	            	        ((View) button1).setOnClickListener(new View.OnClickListener() {
	            	            @Override
	            				public void onClick(View v) {
	            	                setContentView(R.layout.view03b_newmembers);   
		            	        	groupName = 	Groupname.getText().toString();
			                        MemberName= 	(EditText)findViewById(R.id.text_field_two);
			                    	// THE DATA TABLE
			                        dataTable=	 	(TableLayout)findViewById(R.id.data_table);
			                        updateTable();
			    	        		final Button button1 = (Button) findViewById(R.id.add_button); // Create New Group
			    	                ((View) button1).setOnClickListener(new View.OnClickListener() {
			    	                	@Override public void onClick(View v) {addRow();}
			    	                }
			                    	);
			    	        		final Button button2 = (Button) findViewById(R.id.delete_button); // Create New Group
			    	                ((View) button2).setOnClickListener(new View.OnClickListener() {
			    	                	@Override public void onClick(View v) {deleteRow();}
			    	                }
			                    	);
			    	        		final Button button3 = (Button) findViewById(R.id.Accept); // Use Existing Group
			    	                ((View) button3).setOnClickListener(new View.OnClickListener() {
			    	                    @Override
			    						public void onClick(View v) {
			    	                        setContentView(R.layout.view13_overview);
					                        dataTable=	 	(TableLayout)findViewById(R.id.data_table);
					                        updateTableDeposits();
			    	                    }
			    	                });
	                    		}
	            	        }
	                    	);
                    	} //onClick
	                }); //button
	                
	                @SuppressWarnings("unchecked")
	        		final Button button2 = (Button) findViewById(R.id.button2); // Use Existing Group
	                ((View) button2).setOnClickListener(new View.OnClickListener() {
	                    @Override
						public void onClick(View v) {
	                        setContentView(R.layout.view04_existgrp);
	                        
	                        @SuppressWarnings("unchecked")
	                		final Button button2 = (Button) findViewById(R.id.EditGroupButton); // Edit Group
	                        ((View) button2).setOnClickListener(new View.OnClickListener() {
	                            @Override
	        					public void onClick(View v) {
	                                setContentView(R.layout.view05_editgrp);
	                            } //onClick
	                        }); //button
	                    } //onClick
	                }); //button
	            } //onClick
	        }); //button
	    } //try
		catch (Exception e){
			Log.e("ERROR", e.toString());
			e.printStackTrace();
		} //catch
    } //onCreate
    
    
    /**
     * adds a row to the database based on information contained in the
     * add row fields.
     */
    private void addRow()
    {
    	try
    	{
    		// check if the fields are filled
    		if (Groupname.getText().toString().length() > 0 && MemberName.getText().toString().length() > 0)
    		// ask the database manager to add a row given the two strings
    		db.addRow
    		(
    				Groupname.getText().toString(),
    				MemberName.getText().toString()
    		);

    		// request the table be updated
	    	updateTable();
 
			// remove all user input from the Activity
    		emptyFormFields();
    	}
    	catch (Exception e)
    	{
    		Log.e("Add Error", e.toString());
    		e.printStackTrace();
    	}
    }
    
    /**
     * deletes a row from the database with the id number in the corresponding 
     * user entry field
     */
    private void deleteRow()
    {
    	try
    	{
        	// collect the current row information from the database and
        	// store it in a two dimensional ArrayList
        	ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
        	CheckBox checkBox;
        	// iterate the ArrayList, create new rows each time and add them
        	// to the table widget.
        	for (int position=0; position < data.size(); position++){
                checkBox = (CheckBox) findViewById(position);
        		if (checkBox.isChecked()) {
	        		ArrayList<Object> row = data.get(position);
		    		// ask the database manager to delete the row with the give rowID.
		    		db.deleteRow(Long.parseLong(row.get(0).toString()));
        		} // if
        	} // for
		// request the table be updated
		updateTable();

		// remove all user input from the Activity
		emptyFormFields();
    	}
    	catch (Exception e)
    	{
    		Log.e("Delete Error", e.toString());
    		e.printStackTrace();
    	}
    }
     
    /**
     * helper method to empty all the fields in all the forms.
     */
    private void emptyFormFields()
    {
    //    Groupname.setText("");
        MemberName.setText("");
    }
 
    @SuppressWarnings("unused")
	private void updateGroupinfo()
    {
    	TextView group = (TextView) findViewById(R.id.SelectedGroup);
		group.setText(groupName);
    	ArrayList<Object> data = db.getGroupAsArray(groupName);

    }
    
    /**
     * updates the table from the database.
     */
    private void updateTableDeposits()
    {
    	// delete all but the first row.  remember that the count 
    	// starts at one and the index starts at zero
    	while (dataTable.getChildCount() > 1)
    	{
    		// while there are at least two rows in the table widget, delete
    		// the second row.
    		dataTable.removeViewAt(1);
    	}
 
    	// collect the current row information from the database and
    	// store it in a two dimensional ArrayList
    	ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
    	// iterate the ArrayList, create new rows each time and add them
    	// to the table widget.
    	for (int position=0; position < data.size(); position++)
    	{
    		TableRow tableRow= new TableRow(this);
            
    		ArrayList<Object> row = data.get(position);


    		TextView textOne = new TextView(this);
    		textOne.setText(row.get(1).toString());
    		tableRow.addView(textOne);
 
    		TextView textTwo = new TextView(this);
    		textTwo.setText(row.get(0).toString());
    		tableRow.addView(textTwo);
 
    		dataTable.addView(tableRow);
    	}
    }

    /**
     * updates the table from the database.
     */
    private void updateTable()
    {
    	// delete all but the first row.  remember that the count 
    	// starts at one and the index starts at zero
    	while (dataTable.getChildCount() > 1)
    	{
    		// while there are at least two rows in the table widget, delete
    		// the second row.
    		dataTable.removeViewAt(1);
    	}
 
    	// collect the current row information from the database and
    	// store it in a two dimensional ArrayList
    	ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
    	// iterate the ArrayList, create new rows each time and add them
    	// to the table widget.
    	for (int position=0; position < data.size(); position++)
    	{
    		TableRow tableRow= new TableRow(this);
            
    		ArrayList<Object> row = data.get(position);

            // create a CheckBox
            CheckBox checkBox = new CheckBox(this);
            checkBox.setId(position);

    		TextView textOne = new TextView(this);
    		textOne.setText(row.get(1).toString());
    		tableRow.addView(textOne);
 
    		TextView textTwo = new TextView(this);
    		textTwo.setText(row.get(0).toString());
    		tableRow.addView(textTwo);
    		tableRow.addView(checkBox);
 
    		dataTable.addView(tableRow);
    	}
    }
}